<template>
  <Dialog v-model="dialogVisible" title="学生成绩导入" width="400">
    <!-- 考试选择 -->
    <div class="flex items-center my-10px">
      <span class="mr-10px">选择考试</span>
      <el-select v-model="selectedExamId" class="!w-240px" clearable placeholder="请选择考试">
        <el-option
          v-for="item in examOptions"
          :key="item.id"
          :label="item.examName"
          :value="item.id"
        />
      </el-select>
    </div>
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl + '?updateSupport=' + updateSupport + '&examId=' + selectedExamId"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox v-model="updateSupport" />
            是否更新已经存在的学生成绩数据
          </div>
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ExamScoreApi } from '@/api/system/examscore'
import { ExamTestApi, ExamTestVO } from '@/api/system/examtest'
import { getAccessToken, getTenantId } from '@/utils/auth'
import download from '@/utils/download'

defineOptions({ name: 'ExamScoreImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/system/exam-score/import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的学生成绩数据
const selectedExamId = ref<number>() // 选中的考试ID
const examOptions = ref<ExamTestVO[]>([]) // 考试选项列表

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  updateSupport.value = 0
  fileList.value = []
  selectedExamId.value = undefined
  await resetForm()
  // 获取考试列表
  const examData = await ExamTestApi.getSimpleExamTestList()
  examOptions.value = examData.list || []
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  if (!selectedExamId.value) {
    message.error('请选择考试')
    return
  }
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  // 拼接提示语
  const data = response.data
  let text = '上传成功数量：' + data.createExamScoreNames.length + ';'
  for (let i = 0; i < data.createExamScoreNames.length; i++) {
    text += '< ' + data.createExamScoreNames[i] + ' >'
  }
  text += '\n更新成功数量：' + data.updateExamScoreNames.length + ';'
  for (let i = 0; i < data.updateExamScoreNames.length; i++) {
    text += '< ' + data.updateExamScoreNames[i] + ' >'
  }
  text += '\n更新失败数量：' + Object.keys(data.failureExamScoreNames).length + ';'
  for (const key in data.failureExamScoreNames) {
    text += '< ' + key + ': ' + data.failureExamScoreNames[key] + ' >'
  }
  message.alert(text)
  formLoading.value = false
  dialogVisible.value = false
  // 发送操作成功的事件
  emits('success')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置上传状态和文件
  formLoading.value = false
  await nextTick()
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 下载导入模板 */
const importTemplate = async () => {
  if (!selectedExamId.value) {
    message.error('请先选择考试')
    return
  }
  const selectedExam = examOptions.value.find(exam => exam.id === selectedExamId.value)
  const examName = selectedExam ? selectedExam.examName : '未知考试'
  const res = await ExamScoreApi.importTemplate()
  download.excel(res, `学生成绩导入模板-${examName}.xls`)
}
</script>